<?php

namespace app\api\controller;

use app\admin\controller\crud\Log;
use app\admin\model\Technician;
use app\api\model\FareOrder;
use app\api\model\TechnicianMoneyLog;
use app\common\controller\Frontend;
use think\facade\Db;

class Balance extends Frontend
{
    protected array $noNeedPermission = ['*'];

    /**
     * 余额支付
     */
    public function pay ()
    {
        $order_sn = $this->request->post('order_sn');
        $pay_password = $this->request->post('pay_password');
        if (empty($order_sn)) {
            $this->error('订单号不能为空！');
        }
        if (empty($pay_password)) {
            $this->error('支付密码不能为空！');
        }
        $orderModel = new \app\api\model\Order();
        $orderInfo = $orderModel->where('order_sn', $order_sn)->find();
        if (empty($orderInfo)) {
            $this->error('订单不存在！');
        }
        if ($orderInfo->order_state != 'ToBePaid') {
            $this->error('订单状态不正确！');
        }
        $userInfo = \app\common\model\User::where('id', $this->auth->id)->find();
        if (empty($userInfo->pay_password)) {
            $this->error('支付密码未设置，请设置支付密码！');
        }
        if (md5($pay_password) != $userInfo->pay_password) {
            $this->error('支付密码不正确！');
        }
        if ($userInfo->money < $orderInfo->service_total_price) {
            $this->error('余额不足！');
        }


        #加入余额变动表
        $userMoneyLog = new \app\common\model\UserMoneyLog();
        $userMoneyLogInfo = $userMoneyLog
            ->where('user_id', $userInfo->id)
            ->order('create_time', 'desc')
            ->find();
        if (!$userMoneyLogInfo) {
            $userMoneyLog->before = 0;
        } else {
            $userMoneyLog->before = $userMoneyLogInfo->after;
        }
        $userMoneyLog->money = $orderInfo->service_total_price;
        $userMoneyLog->user_id = $userInfo->id;
        $userMoneyLog->after = bcsub($userMoneyLog->before, $orderInfo->service_total_price, 2);
        $userMoneyLog->memo = '支付订单' . $orderInfo->order_sn;
        $userMoneyLog->create_time = date('Y-m-d H:i:s', time());
        $userMoneyLog->type = 2;

        Db::startTrans();
        try {
            #扣除用户余额
            $userInfo->money = bcsub($userInfo->money, $orderInfo->service_total_price, 2);
            $userInfo->save();
            $userMoneyLog->save();

            $orderInfo->pay_way = 'balance'; //支付方式
            $orderInfo->payment_order_sn = 'YE' . date('YmdHis', time()) . time() . rand(1000, 9999); //支付订单号
            $orderInfo->service_reality_price = $orderInfo->service_total_price; //实际支付金额
            $orderInfo->payment_time = date('Y-m-d H:i:s', time()); //支付成功时间

            #记录订单状态
            setOrderStateLog($orderInfo->id, 'Paid');
            setOrderStateLog($orderInfo->id, 'Received');

            if ($orderInfo->type == 1) {
                $orderInfo->order_state = 'Received'; //订单状态 已接单
            } else {
                $orderInfo->order_state = 'Start'; //订单状态 已支付
                setOrderStateLog($orderInfo->id, 'SetOut');
                setOrderStateLog($orderInfo->id, 'Reach');
                setOrderStateLog($orderInfo->id, 'Start');
            }

            #写入时间预约
            Db::name('order_reservation')->insert([
                'user_id'          => $this->auth->id,
                'technician_id'    => $orderInfo->technician_id,
                'reservation_time' => $orderInfo->service_start_time,
                'order_sn'         => $orderInfo->order_sn,
                'create_time'      => date('Y-m-d H:i:s', time()),
            ]);

            $orderInfo->save();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            \think\facade\Log::error('订单 ' . $orderInfo->order_sn . ' 支付失败- ' . $e->getMessage());
            $this->error('支付失败！');
        }
        #给技师发送短信
        try {
            $username = \app\admin\model\Technician::where('technician_id', $orderInfo->technician_id)->value('username');
            sms_send($orderInfo->technician_tel, 'technician_order', ['account' => $username]);
        } catch (\Exception $e) {
            \think\facade\Log::error('支付回调-技师接单短信发送失败' . $e->getMessage());
        }
        $this->success('支付成功！');
    }

    /**
     * 余额支付车费
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function farePay (): void
    {
        $order_sn = $this->request->post('fare_order_sn');
        $pay_password = $this->request->post('pay_password');
        if (empty($order_sn)) {
            $this->error('订单号不能为空！');
        }
        if (empty($pay_password)) {
            $this->error('支付密码不能为空！');
        }
        $orderModel = new FareOrder();
        $orderInfo = $orderModel->where('fare_order_sn', $order_sn)->find();
        if (empty($orderInfo)) {
            $this->error('订单不存在！');
        }
        if ($orderInfo->fare_state != 'ToBePaid') {
            $this->error('订单状态不正确！');
        }
        $userInfo = \app\common\model\User::where('id', $this->auth->id)->find();
        if (empty($userInfo->pay_password)) {
            $this->error('支付密码未设置，请设置支付密码！');
        }
        if (md5($pay_password) != $userInfo->pay_password) {
            $this->error('支付密码不正确！');
        }
        if ($userInfo->money < $orderInfo->service_total_price) {
            $this->error('余额不足！');
        }

        $orderInfo->fare_pay_state = 'balance'; //支付方式
        $orderInfo->fare_state = 'Paid'; //订单状态 已支付
        $orderInfo->fare_technician_id = 'YE' . date('YmdHis', time()) . time() . rand(1000, 9999); //支付订单号
        $orderInfo->fare_pay_price = $orderInfo->fare_price; //实际支付金额
        $orderInfo->fare_pay_time = date('Y-m-d H:i:s', time()); //支付成功时间

        #加入余额变动表
        $userMoneyLog = new \app\common\model\UserMoneyLog();
        $userMoneyLogInfo = $userMoneyLog
            ->where('user_id', $userInfo->id)
            ->order('create_time', 'desc')
            ->find();
        if (!$userMoneyLogInfo) {
            $userMoneyLog->before = 0;
        } else {
            $userMoneyLog->before = $userMoneyLogInfo->after;
        }
        $userMoneyLog->money = $orderInfo->fare_price;
        $userMoneyLog->user_id = $userInfo->id;
        $userMoneyLog->after = bcsub($userMoneyLog->before, $orderInfo->fare_price, 2);
        $userMoneyLog->memo = '支付车费附加订单' . $orderInfo->fare_order_sn;
        $userMoneyLog->create_time = date('Y-m-d H:i:s', time());
        $userMoneyLog->type = 2;

        #加入技师余额变动表
        $TechnicianMoneyLog = new TechnicianMoneyLog();
        $technicianMoneyLogInfo = $TechnicianMoneyLog->where('technician_id', $orderInfo->technician_id)->order('create_time', 'desc')->find();
        if (!$technicianMoneyLogInfo) {
            $TechnicianMoneyLog->before = 0;
        } else {
            $TechnicianMoneyLog->before = $technicianMoneyLogInfo->after;
        }
        $TechnicianMoneyLog->money = $orderInfo->fare_pay_price;
        $TechnicianMoneyLog->technician_id = $orderInfo->technician_id;
        $TechnicianMoneyLog->after = bcadd($TechnicianMoneyLog->before, $orderInfo->fare_price, 2);
        $TechnicianMoneyLog->memo = '车费附加订单' . $orderInfo->fare_order_sn;
        $TechnicianMoneyLog->create_time = date('Y-m-d H:i:s', time());
        $TechnicianMoneyLog->type = 2;//1正常收入 2 车费  3 提现 4 手动增加余额 5手动减少余额
        $TechnicianMoneyLog->order_id = $orderInfo->fare_id;

        Db::startTrans();
        try {

            #技师余额修改
            $info = Technician::where('technician_id', $orderInfo->technician_id)->find();
            $info->money = bcadd($info->money, $orderInfo->fare_price, 2);
            $info->save();

            #扣除用户余额
            $userInfo->money = bcsub($userInfo->money, $orderInfo->fare_price, 2);
            $userInfo->save();
            $userMoneyLog->save();
            $orderInfo->save();
            $TechnicianMoneyLog->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            \think\facade\Log::error('订单 ' . $orderInfo->fare_order_sn . ' 支付失败- ' . $e->getMessage());
            $this->error('支付失败！');
        }
        $this->success('支付成功！');
    }
}